//
//  MFWMessagenCenter.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-9-13.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//


#define msErrorDomain                   @"msErrorDomain"
#define msErrorCodeMissingParam                 101
#define msErrorCodeServiceNotResponding         201
#define msErrorCodeServiceRespondFailed         202
#define msErrorCodeServiceWrongDataStructure    210

#define MFWClick_MFWSDK_EventCode_mfwsdk_msg    @"mfwsdk_msg"
#define MFWClick_MFWSDK_EventCode_mfwsdk_push	@"mfwsdk_push"

#define MFWClick_MFWSDK_Key_alert 	@"alert"
#define MFWClick_MFWSDK_Key_click 	@"click"
#define MFWClick_MFWSDK_Key_command @"command"
#define MFWClick_MFWSDK_Key_msg_type	@"msg_type"
#define MFWClick_MFWSDK_Key_msg_id	@"msg_id"
#define MFWClick_MFWSDK_Key_status	@"status"


#import "MFWMessageCenter.h"
#import "NSString+ShareJump.h"

NSString *const MFWMessageCenterUnreadMessageCountInMessageCenterDidChange =
                @"MFWMessageCenterUnreadMessageCountInMessageCenterDidChange";

@interface MFWMessageCenter()
/** 当前所有消息（按时间戳从旧到新排序） added by hanxin 20130623 */
@property (nonatomic,strong) NSMutableArray* arrayMessage;

@property (nonatomic,strong) NSMutableDictionary* isReadMessages;


@property (nonatomic,assign) BOOL remoteMessageWaitForAlertView;
@property (nonatomic,retain) NSDictionary* remoteMessage;
@property (nonatomic,retain) NSString* urlNeedPush;

@end

@implementation MFWMessageCenter

+ (MFWMessageCenter *)sharedInstance;
{
    static MFWMessageCenter *_sharedInstance = nil;
	if (_sharedInstance == nil)
	{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedInstance = [[MFWMessageCenter alloc] init];
			
        });
	}
	
	return _sharedInstance;
}

- (void)clearCache;
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:msFilePathAllMessageList error:nil];
}

-(void)saveArrayMessage
{
    NSMutableArray* arrayDict = [NSMutableArray arrayWithCapacity:0];
    [self.arrayMessage enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        MSMessage* msg = obj;
        [arrayDict addObject:msg.source];
    }];
    
    [arrayDict writeToFile:msFilePathAllMessageList atomically:YES];
}

-(NSMutableArray*)arrayMessage
{
    if (!_arrayMessage) {
        _arrayMessage = [self loadArrayMessage];
    }
    
    return _arrayMessage;
}

-(MSMessage*)messageWithDictionary:(NSDictionary*)dict
{
    MSMessage* message = [MSMessage messageWithDictionary:dict];
    if ([message.msgType isEqualToString:MSMessageTypeFeedback]) {
        message = [MSMessageFeedback messageWithDictionary:dict];
    }
    if ([message.msgType isEqualToString:MSMessageTypeSystem]) {
        message = [MSMessageSystem messageWithDictionary:dict];
    }
    
    return message;
}

-(NSMutableArray*)loadArrayMessage
{
    NSArray* arrayDict = [NSArray arrayWithContentsOfFile:msFilePathAllMessageList];
    
    NSMutableArray* arrayMessage = [NSMutableArray arrayWithCapacity:0];
    [arrayDict enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSDictionary* dict = obj;
        MSMessage* msg = [self messageWithDictionary:dict];
        [arrayMessage addObject:msg];
    }];
    
    return arrayMessage;
}

- (void)markAllMessageHasBeenRead;
{
    NSArray *allUnreadMessages = [self getMessageListByMsgType:MSMessageTypeAll isRead:NO];
    
    NSUInteger count = [allUnreadMessages count];
    if (count > 0)
    {
        NSMutableSet *unreadMessageIdSet = [NSMutableSet set];
        for (int i = 0; i < count; i++)
        {
            MSMessage *message = [allUnreadMessages objectAtIndex:i];
            NSString *identifier = [NSString stringWithFormat:@"%@%@", message.msgType, message.msgId];
            [unreadMessageIdSet addObject:identifier];
            [message.source setObject:@"1" forKey:MSMessageKeyIsRead];
        }
        
        [self.arrayMessage enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            MSMessage *msg = obj;
            NSString *identifier = [NSString stringWithFormat:@"%@%@", msg.msgType, msg.msgId];
            if ([unreadMessageIdSet containsObject:identifier])
            {
                [msg.source setObject:@"1" forKey:MSMessageKeyIsRead];
            }
        }];
        
        [self saveArrayMessage];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:MFWMessageCenterUnreadMessageCountInMessageCenterDidChange
                                                            object:nil];
    }
}

-(void)setMessage:(MSMessage*)message isRead:(BOOL)isRead
{
//    // 发送MFWClick消息已读事件
//    [MFWClick event:MFWClick_MFWSDK_EventCode_mfwsdk_msg publicAttributesBlock:^NSDictionary *{
//        return @{MFWClick_MFWSDK_Key_msg_type:message.msgType
//                 ,MFWClick_MFWSDK_Key_msg_id:message.msgId
//                 ,MFWClick_MFWSDK_Key_status:@"1"};// 1表示已读
//    } privateAttributesBlock:nil];
    
    // 更新当前消息
    [message.source setObject:isRead?@"1":@"0" forKey:MSMessageKeyIsRead];
    // 更新内存中的消息列表
    [self.arrayMessage enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        MSMessage* msg = obj;
        if ([msg.msgType isEqualToString:message.msgType] && [msg.msgId isEqualToString:message.msgId]) {
            [msg.source setObject:isRead?@"1":@"0" forKey:MSMessageKeyIsRead];
        }
    }];
    // 保存到本地
    [self saveArrayMessage];
    
    if (![self.isReadMessages objectForKey:message.msgType]) {
        // 还没有此类型的已读消息msgId列表，则创建一个
        [self.isReadMessages setObject:[NSMutableArray arrayWithCapacity:0] forKey:message.msgType];
    }
    
    NSMutableArray* array = [self.isReadMessages objectForKey:message.msgType];
    
    // 在本地已读缓存中找到msgId
    id foundItem = nil;
    for (id isReadMsgId in array) {
        if ([isReadMsgId isEqualToString:message.msgId]) {
            // 在列表中找到，记下地址
            foundItem = isReadMsgId;
        }
    }
    
    if (isRead) {
        if (!foundItem) {
            // 内存中没有，则加到内存列表头部
            [array addObject:message.msgId];
            // 将内存中列表同步到本地缓存
            [self.isReadMessages writeToFile:msFilePathIsReadMessageList atomically:YES];
        }else{
            // 本来就是已读状态了，就不再处理了
        }
    }else{
        [array removeObject:foundItem];
        [self.isReadMessages writeToFile:msFilePathIsReadMessageList atomically:YES];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:MFWMessageCenterUnreadMessageCountInMessageCenterDidChange
                                                        object:nil];
}

// 异步上传即时消息接口 added by hanxin 20130621
-(void)sendFeedBackMessage:(NSString*)message completion:(void(^)(BOOL success, NSError* error))completion
{
    MFWHttpRequest* request = [MFWHttpRequest dataRequest];
    request.httpMethod = kRequestHttpMethodPost;
    request.requestApi = kAPI_MessageFeedback;
    

//    [request.requestParams setValue:[MFWSdkEnvironment sharedInstance].pushDeviceToken
//                                      forKey:@"device_token"];
    [request.requestParams setValue:@"feedback"
                                      forKey:@"msg_type"];
    [request.requestParams setValue:message
                                      forKey:@"msg_content"];
    
    request.requestCompleteCallback = ^(MFWHttpRequest *request, NSData* responseData, MFWJson* parsedJson, NSError* error) {
        // 无回调，不需处理，直接返回
        if (!completion) {
            return;
        }
        
        if (!error)
        {
            error = [MFWServiceUtils parseMFWServiceError:parsedJson];
        }
        // 无任何返回结果，或解析失败，直接返回
        if(error)
        {
            completion(NO,error);
            return;
        }
        
        // 在返回前，重新获取一下消息，取回服务端刚入库的意见反馈及其他消息
        [self requestMessageMoreListCompletion:^(BOOL success, NSArray *array, NSError *error) {
            completion(YES,nil);
        }];
    
    };
    
    [[MFWHttpEngine sharedInstance] addRequest:request];
}


// 请求全部类型的消息（根据时间戳增量获取） added by hanxin 20130621
-(MFWHttpRequest*)requestMessageMoreListCompletion:(void(^)(BOOL success, NSArray* array,NSError* error))completion
{
    NSString* msgType = MSMessageTypeAll;
    
    if (msgType.length == 0) {
        NSError* error = [NSError errorWithDomain:msErrorDomain code:msErrorCodeMissingParam userInfo:@{@"description":@"缺失参数MsgType"}];
        completion(NO,nil,error);
        return nil;
    }
    
    NSArray* messageArray = self.arrayMessage;
    MSMessage* lastMessage = [messageArray lastObject];
    
    MFWHttpRequest* request = [MFWHttpRequest dataRequest];
    request.httpMethod = kRequestHttpMethodPost;
    request.requestApi = kAPI_MessageGet;

//    [request.requestParams setValue:[MFWSdkEnvironment sharedInstance].pushDeviceToken
//                                      forKey:@"device_token"];
    [request.requestParams setValue:msgType
                                      forKey:@"msg_type"];
    if (lastMessage && lastMessage.timestamp) {
        [request.requestParams setValue:lastMessage.timestamp
                                          forKey:@"last_timestamp"];
    }

    request.requestCompleteCallback = ^(MFWHttpRequest *request, NSData* responseData, MFWJson* parsedJson, NSError* error) {
        
        if (!error)
        {
            error = [MFWServiceUtils parseMFWServiceError:parsedJson];
        }
        
        if (!error && parsedJson) {
            
            MFWJson *dataJson = [parsedJson jsonForKey:@"data"];
            MFWJson *listJson = [dataJson jsonForKey:@"list"];
            
            id obj = listJson.jsonObj;
            
            if ([obj isKindOfClass:[NSArray class]]) {
                NSArray* array = obj;
                NSMutableArray* mutableMessages = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary* dict in array) {
                    
                    MSMessage* message = [self messageWithDictionary:dict];
                    
                    if (message) {
                        [self updateMessageIsRead:message];
                        [mutableMessages addObject:message];
                    }
                }
                
                // 附加到成员属性中
                [self.arrayMessage addObjectsFromArray:mutableMessages];
                // 按从旧到新排序
                [self.arrayMessage sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                    MSMessage* msg1 = obj1;
                    MSMessage* msg2 = obj2;
                    return [msg1 compareTimeStamp:msg2];
                }];
                
                // 保存到本地
                [self saveArrayMessage];
                
                if (completion) {
                    completion(YES,mutableMessages,nil);
                }
            }
            else
            {
                NSString* errorMessage = [NSString stringWithFormat:@"应该为NSArray接口，但收到的是%@",[obj class]];
                NSLog(@"[MFWSDK]%@", errorMessage);
                if (completion) {
                    completion(NO,nil,[NSError errorWithDomain:msErrorDomain
                                                          code:msErrorCodeServiceWrongDataStructure
                                                      userInfo:@{@"description":errorMessage}]
                               );
                }
            }
            
        }else{
            if (completion) {
                completion(NO,nil,error);
            }
            
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:MFWMessageCenterUnreadMessageCountInMessageCenterDidChange
                                                            object:nil];
    } ;
    
    // 开始请求
    [[MFWHttpEngine sharedInstance] addRequest:request];
    // 返回链接
    return request;
    
}

// 请求指定类型的消息（根据时间戳增量获取）（实际上会取msg_type=all，然后挑出需要的消息类型通过回调返回） added by hanxin 20130621
-(MFWHttpRequest*)requestMessageMoreListByMessageType:(NSString*)msgType completion:(void (^)(BOOL, NSArray *, NSError *))handler
{
    return [self requestMessageMoreListCompletion:^(BOOL success, NSArray *originArray, NSError *error) {
        if (handler) {
            
            NSMutableArray* array = nil;
            if (success && originArray) {
                array = [NSMutableArray arrayWithCapacity:0];
                // 挑出来需要的消息类型
                [originArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    MSMessage* msg = obj;
                    if ([msg.msgType isEqualToString:msgType]) {
                        [array addObject:msg];
                    }
                }];
            }
            
            handler(success,array,error);
        }
    }];
}

// 获取本地已取到的消息（排除意见反馈类型中的用户发送的）：所有类型  added by hanxin 20130621
-(NSArray*)getMessageListInMessageCenter
{
    NSMutableArray* array = [NSMutableArray arrayWithCapacity:0];
    [self.arrayMessage enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        
        BOOL need2Add = YES;
        MSMessage* msg = obj;
        
        if ([msg.msgType isEqualToString:MSMessageTypeFeedback]) {
            MSMessageFeedback* feedbackMsg = [[MSMessageFeedback alloc]initWithMessage:msg];
            // 来自用户提交的意见反馈不出现在消息中心得列表中
            if (feedbackMsg.fromUser) {
                need2Add = NO;
            }
        }
        
        if (need2Add) {
            [array addObject:msg];
        }
    }];
    
    return array;
}

-(NSInteger)getUnreadMessageCountInMessageCenter
{
    NSArray* array = [self getMessageListInMessageCenter];
    __block NSInteger unreadCount = 0;
    
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        MSMessage* msg = obj;
        if (!msg.isRead) {
            unreadCount++;
        }
    }];
    
    return unreadCount;
}

// 获取本地已取到的消息：指定类型  added by hanxin 20130621
-(NSArray*)getMessageListByMsgType:(NSString*)msgType
{
    NSMutableArray* array = [NSMutableArray arrayWithCapacity:0];
    [self.arrayMessage enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        
        MSMessage* msg = obj;
        if ([msg.msgType isEqualToString:msgType]) {
            [array addObject:msg];
        }
    }];
    
    return array;
}

// 获取已读未读的消息
-(NSArray*)getMessageListByMsgType:(NSString*)msgType isRead:(BOOL)aIsRead
{
    NSMutableArray* array = [NSMutableArray arrayWithCapacity:0];
    [self.arrayMessage enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        
        MSMessage* msg = obj;
        if ([msgType isEqualToString:MSMessageTypeAll] || [msgType isEqualToString:msg.msgType])
        {
            if (msg.isRead == aIsRead) {
                [array addObject:msg];
            }
        }

    }];
    
    return array;
}


#pragma mark - 活动类型消息处理（内部）

// 已读消息，格式 @{@"activity":@[@"17",@"11"]}
-(NSMutableDictionary*)isReadMessages
{
    if (!_isReadMessages) {
        // 加载本地已读缓存
        _isReadMessages = [NSMutableDictionary dictionaryWithDictionary:[NSDictionary dictionaryWithContentsOfFile:msFilePathIsReadMessageList]];
    }
    
    return _isReadMessages;
}



-(void)updateMessageIsRead:(MSMessage*)message
{
    // 如果已经存在，则不使用本地的已读缓存msgId列表来更新message的isRead已读状态
    if ([message.source objectForKey:MSMessageKeyIsRead]) {
        return;
    }
    
    NSMutableArray* array = [self.isReadMessages objectForKey:message.msgType];
    
    // 在本地已读缓存中找到msgId
    BOOL foundItem = NO;
    for (NSString* isReadMsgId in array) {
        if ([isReadMsgId isEqualToString:message.msgId]) {
            // 在列表中找到，记下地址
            foundItem = YES;
        }
    }
    
    if (foundItem) {
        [message.source setObject:@"1" forKey:MSMessageKeyIsRead];
    }
}

// iOS设备注册更新接口
-(void)registerDeviceToken:(NSData*)deviceTokenData withInfo:(NSDictionary *)info
{
    NSString *device_token = [NSString stringWithFormat:@"%@", deviceTokenData];
    device_token = [device_token stringByReplacingOccurrencesOfString: @"<" withString: @""];
    device_token = [device_token stringByReplacingOccurrencesOfString: @">" withString: @""];
    device_token = [device_token stringByReplacingOccurrencesOfString: @" " withString: @""];
    
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DeviceToken" message:device_token delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
//    [alert show];
    
    MFWSdkEnvironment *environment = [MFWSdkEnvironment sharedInstance];
    
    if(device_token.length == 0)
    {
        return;
    }
    environment.pushDeviceToken = device_token;
    
    MFWHttpRequest* request = [MFWHttpRequest dataRequest];
    request.httpMethod = kRequestHttpMethodPost;
    request.requestApi = kAPI_PushTokenReg;
    
    // 公共基础参数会里已经含有该值（environmen.pushDeviceToken）
    if (!environment.isDEBUG)
    {
        [request.requestParams setValue:device_token
                                          forKey:@"device_token"];
    }
    
    [request.requestParams setValue:environment.hardwareModel
                                      forKey:@"device_model"];
    [request.requestParams setValue:environment.deviceName
                                      forKey:@"device_name"];
    
    
    
    [[MFWHttpEngine sharedInstance] addRequest:request];
    
}

-(void)processRemoteNotificationWithCommand:(NSDictionary *)userInfo fromLaunch:(BOOL)bFromLaunch;
{
    if(userInfo == nil)
    {
        return;
    }
    
    BOOL isAppLaunchedByPush = bFromLaunch;// App是否因为推送消息而启动
    
    switch ([[UIApplication sharedApplication] applicationState]) {
        case UIApplicationStateBackground:
            NSLog(@"UIApplicationStateBackground");
            break;
            
        case UIApplicationStateInactive:
            NSLog(@"UIApplicationStateInActive");
            
            [self eventPushClick:@"ios" pushUserInfo:userInfo];
            self.remoteMessageWaitForAlertView = NO;
            
            if ([UIApplication sharedApplication].keyWindow) {
                [self processMessageWithCommandInside:userInfo];
            }else{
                self.remoteMessage = userInfo;
            }
            
            break;
            
        case UIApplicationStateActive:
            
            // 如果是在前台运行，则弹出对话框确认
            NSLog(@"UIApplicationStateActive");
            
            if (isAppLaunchedByPush)
            {
                [self eventPushClick:@"ios" pushUserInfo:userInfo];
                [self processMessageWithCommandInside:userInfo];
            }
            else
            {
                BOOL process = [self processMessageWithCommandInside:userInfo];
                if (process) break;
                
                id alertObject = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
                NSString* alert = @"";
                if ([alertObject isKindOfClass:[NSDictionary class]])
                {
                    alert = [((NSDictionary*)alertObject) objectForKey:@"body"];
                }
                else if ([alertObject isKindOfClass:[NSString class]])
                {
                    alert = (NSString*)alertObject;
                }
                
                NSString* buttonString = nil;
                NSString* titleString = @"收到远程通知!";
                
                
                if([userInfo objectForKey:@"button"])
                {
                    buttonString = [userInfo objectForKey:@"button"];
                }
                else
                {
                    buttonString = @"确定";
                }
                
                if([userInfo objectForKey:@"title"])
                {
                    titleString = [userInfo objectForKey:@"title"];
                }

                UIAlertView * al = [[UIAlertView alloc]initWithTitle:titleString message:alert delegate:self cancelButtonTitle:@"取消" otherButtonTitles:buttonString, nil];
                
                [al show];
                
                self.remoteMessageWaitForAlertView = YES;
                
                self.remoteMessage = userInfo;
            }
            
            break;
            
        default:
            break;
    }

}

-(BOOL)openUrl:(NSString*)urlString
{
    if (!urlString || ![urlString isKindOfClass:[NSString class]])
    {
        return NO;
    }

    if([[[NSURL URLWithString:urlString] scheme] length] == 0)
    {
        // 尝试自动补全
        urlString = [@"http://" stringByAppendingString:urlString];
    }
    
    return [[UIApplication sharedApplication] openURL:[NSURL URLWithString: urlString]];
}

-(BOOL)processMessageWithCommandInside:(NSDictionary*)pushUserInfo
{
    NSLog(@"processMessageWithCommandInside:%@",pushUserInfo);
    
    BOOL process = NO;
    
    // 处理一般url
    NSString* commandString = [[pushUserInfo objectForKey:@"command"] copy];
    if(!process && commandString.length > 0 && [commandString hasPrefix:@"url:"])
    {
        NSString* commandBody = [commandString stringByReplacingOccurrencesOfString:@"url" withString:@""];
        if([commandBody hasPrefix:@":"])
        {
            commandBody = [commandBody substringFromIndex:1];
        }
        NSString* url = commandBody;
        
        if (url.length > 0 && [UIApplication sharedApplication].keyWindow)
        {
                // 判断外部是否可以处理
            if (self.blockCanHandlePushNotificationUrl
                && self.blockCanHandlePushNotificationUrl(url))
            {
                // 交到外部处理，不用默认的处理
                process = YES;
            }
            else
            {
                // 使用默认的处理
                process = [self openUrl:url];
            }
        }
    }


    // 完全版推送（android使用）
    NSString* jumpStr = [[pushUserInfo objectForKey:@"jump"] copy];
    if (!process && jumpStr.length > 0) {
        
        NSString* type = [jumpStr shareJumpQueryType];
        NSDictionary* params = [jumpStr shareJumpQueryParams];
        
        if (self.blockCanHandlePushNotificationJump
            && self.blockCanHandlePushNotificationJump(type,params)) {
            // 如果外部可以处理的跳转
            process = YES;
        }
    }
    
    // 精简版推送（iOS使用）
    NSString* jStr = [[pushUserInfo objectForKey:@"j"] copy];
    if (!process && jStr.length > 0) {
        NSArray *keyAndValue = [jStr componentsSeparatedByString:@","];
        // 如果jStr.length> 0 则数组count一定大于0
        NSString *type = keyAndValue.firstObject;
        keyAndValue = [keyAndValue subarrayWithRange:NSMakeRange(1, keyAndValue.count - 1)];
        
        if (self.blockCanHandlePushNotificationJumpValues
            && self.blockCanHandlePushNotificationJumpValues(type,keyAndValue)) {
            // 如果外部可以处理的跳转
            process = YES;
        }
    }
    
    return process;
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        [self eventPushClick:@"ok" pushUserInfo:self.remoteMessage];
        
        // 点击了确定按钮，进行处理
        [self processMessageWithCommandInside:self.remoteMessage];
        self.remoteMessage = nil;    // 清空，以避免再触发
        
        self.remoteMessageWaitForAlertView = NO;
        
    }else{
        [self eventPushClick:@"cancel" pushUserInfo:self.remoteMessage];
    }
}

#pragma mark MFWClick相关

/**
 点击push事件
 click：
 ios：    来自ios的消息系统
 ok：     来自App内点击确定按钮
 cancel： 来自App内取消按钮
 */
-(void)eventPushClick:(NSString*)click pushUserInfo:(NSDictionary*)pushUserInfo
{

    NSString* alert = [self getAlertFromPushUserInfo:pushUserInfo];
    NSString* command = [[pushUserInfo objectForKey:@"command"] copy];
    
    if(click.length == 0){click = @"";}
    if(alert.length == 0){alert = @"";}
    if(command.length == 0){command = @"";}
    
//    [MFWClick event:MFWClick_MFWSDK_EventCode_mfwsdk_push publicAttributesBlock:^NSDictionary *{
//        return @{MFWClick_MFWSDK_Key_click:click
//                 ,MFWClick_MFWSDK_Key_alert:alert};
//    } privateAttributesBlock:^NSDictionary *{
//        return @{MFWClick_MFWSDK_Key_command:command};
//    }];
}

-(NSString*)getAlertFromPushUserInfo:(NSDictionary*)pushUserInfo
{
    NSString* alert = @"";
    id alertObject = [[pushUserInfo objectForKey:@"aps"] objectForKey:@"alert"];
    if ([alertObject isKindOfClass:[NSDictionary class]]) {
        alert = [((NSDictionary*)alertObject) objectForKey:@"body"];
    }
    else if ([alertObject isKindOfClass:[NSString class]])
    {
        alert = (NSString*)alertObject;
    }
    
    return [alert copy];
}
@end
